const http = require("http")
const fs = require("fs")

var server = http.createServer()

function handleIncomingStream(incomingStream) {
  return JSON.parse(incomingStream)
}

function writeFile2Disk(file_data, file_name) {

  let promise = new Promise((resolve, reject) => {
    // file_data has been translated to json(string)
    fs.writeFile(file_name, new Buffer(file_data), err => {
      if (!err) resolve()
      else reject(err)
    })
  })

  return promise
}

server.on("request", (request, response) => {
  request.on("data", data => {

    if (request.url === "/note_submit") {
      // tanslate the incoming data to object
      let incoming_data = handleIncomingStream(data)
      writeFile2Disk(incoming_data.file_content, incoming_data.file_name)
        .then(() => {
          response.statusCode = 200
          response.end("ok")
        }, err => {
          console.error(err)
        })
    }
  })

})

console.info(require("process").execPath)

server.listen(1601)